<template>
  <div class="video-player" :class="{ fullscreen: isFullscreen }">
    <div
      class="video-container"
      :class="{ 'disable-click': props.disableClick }"
      @click="togglePlay"
      @dblclick="toggleFullscreen"
    >
      <video
        ref="videoRef"
        :src="videoSrc"
        :poster="poster"
        @loadedmetadata="onLoadedMetadata"
        @timeupdate="onTimeUpdate"
        @ended="onEnded"
        @play="isPlaying = true"
        @pause="isPlaying = false"
        preload="metadata"
        controlsList="nodownload nofullscreen noremoteplayback"
        disablePictureInPicture
      />

      <!-- 播放/暂停按钮覆盖层 -->
      <div
        class="play-overlay"
        v-show="
          !props.isPlaying && !showControls && !(isFullscreen || !props.hideControls)
        "
        @click="togglePlay"
      >
        <div class="play-button">
          <el-icon size="48">
            <VideoPlay />
          </el-icon>
        </div>
      </div>

      <!-- 加载中 -->
      <div class="loading-overlay" v-show="isLoading">
        <el-icon size="32" class="loading-icon">
          <Loading />
        </el-icon>
      </div>
    </div>

    <!-- controls：全屏时强制显示，非全屏时按hide-controls控制 -->
    <div
      v-if="isFullscreen || !props.hideControls"
      class="video-controls"
      :class="{ show: showControls || isFullscreen }"
      @mouseenter="showControls = true"
    >
      <div class="controls-row">
        <!-- 播放/暂停 -->
        <el-button
          :icon="isPlaying ? VideoPause : VideoPlay"
          @click="togglePlay"
          size="small"
          circle
          class="control-btn"
        />
        <!-- 快退 -->
        <el-button
          :icon="DArrowLeft"
          @click="seek(-10)"
          size="small"
          circle
          class="control-btn"
        />
        <!-- 进度条 -->
        <div class="progress-container">
          <el-slider
            v-model="currentTime"
            :max="duration"
            :step="0.1"
            :show-tooltip="false"
            @change="seekTo"
            class="progress-slider"
            size="small"
          />
        </div>
        <!-- 快进 -->
        <el-button
          :icon="DArrowRight"
          @click="seek(10)"
          size="small"
          circle
          class="control-btn"
        />
        <!-- 时间显示 -->
        <div class="time-display">
          {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
        </div>
        <!-- 音量控制 -->
        <div class="volume-control">
          <el-button
            :icon="isMuted ? Mute : Microphone"
            @click="toggleMute"
            size="small"
            circle
            class="control-btn"
          />
        </div>
        <!-- 缩小/全屏 -->
        <el-button
          :icon="isFullscreen ? Aim : FullScreen"
          @click="toggleFullscreen"
          size="small"
          circle
          class="control-btn"
        />
      </div>
    </div>

    <!-- 快进快退提示 -->
    <div class="seek-indicator" v-show="seekIndicator.show">
      <el-icon size="24">
        <DArrowLeft v-if="seekIndicator.direction === 'backward'" />
        <DArrowRight v-if="seekIndicator.direction === 'forward'" />
      </el-icon>
      <span>{{ seekIndicator.text }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import {
  VideoPlay,
  VideoPause,
  FullScreen,
  Aim,
  Microphone,
  Mute,
  Loading,
  DArrowLeft,
  DArrowRight,
} from "@element-plus/icons-vue";
import Hls from "hls.js";
import {API_CONFIG} from "../api";

const props = defineProps({
  videoSrc: {
    type: String,
    default: "",
  },
  poster: {
    type: String,
    default: "",
  },
  autoplay: {
    type: Boolean,
    default: false,
  },
  hideControls: {
    type: Boolean,
    default: false,
  },
  disableClick: {
    type: Boolean,
    default: false,
  },
  isPlaying: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["play", "pause", "ended", "timeupdate"]);

const videoRef = ref();
let hls = null;
const isPlaying = ref(false);
const isLoading = ref(false);
const isFullscreen = ref(false);
const showControls = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const volume = ref(100);
const isMuted = ref(false);

const seekIndicator = ref({
  show: false,
  direction: "forward",
  text: "",
});

let controlsTimer = null;
let seekTimer = null;

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return "00:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 播放/暂停
const togglePlay = () => {
  console.log('点击了视频全屏的播放按钮');
  console.log('props.disableClick',props.disableClick);
  console.log('videoRef.value',videoRef.value);
  if (props.disableClick) return;
  if (!videoRef.value) return;

  if (isPlaying.value) {
    videoRef.value.pause();
  } else {
    videoRef.value.play();
  }
};

// 跳转到指定时间
const seekTo = (time) => {
  if (videoRef.value) {
    videoRef.value.currentTime = time;
  }
};

// 快进/快退
const seek = (seconds) => {
  if (!videoRef.value) return;

  const newTime = Math.max(
    0,
    Math.min(duration.value, currentTime.value + seconds)
  );
  videoRef.value.currentTime = newTime;

  // 显示快进快退提示
  seekIndicator.value = {
    show: true,
    direction: seconds > 0 ? "forward" : "backward",
    text: `${Math.abs(seconds)}秒`,
  };

  clearTimeout(seekTimer);
  seekTimer = setTimeout(() => {
    seekIndicator.value.show = false;
  }, 1000);
};

// 静音切换
const toggleMute = () => {
  if (!videoRef.value) return;

  if (isMuted.value) {
    videoRef.value.volume = volume.value / 100;
    isMuted.value = false;
  } else {
    videoRef.value.volume = 0;
    isMuted.value = true;
  }
};

// 全屏切换
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
    isFullscreen.value = true;
  } else {
    document.exitFullscreen();
    isFullscreen.value = false;
  }
};

// 视频事件处理
const onLoadedMetadata = () => {
  duration.value = videoRef.value.duration || 0;
  isLoading.value = false;
};

const onTimeUpdate = () => {
  currentTime.value = videoRef.value.currentTime || 0;
  emit("timeupdate", currentTime.value);
};

const onEnded = () => {
  isPlaying.value = false;
  emit("ended");
};

// 键盘快捷键
const handleKeydown = (e) => {
  if (!videoRef.value) return;

  switch (e.code) {
    case "Space":
      e.preventDefault();
      togglePlay();
      break;
    case "ArrowLeft":
      e.preventDefault();
      seek(-10);
      break;
    case "ArrowRight":
      e.preventDefault();
      seek(10);
      break;
    case "KeyF":
      e.preventDefault();
      toggleFullscreen();
      break;
    case "KeyM":
      e.preventDefault();
      toggleMute();
      break;
    case "Escape":
      // 禁用 ESC 键退出全屏
      e.preventDefault();
      e.stopPropagation();
      break;
  }
};

// 鼠标移动显示控制栏
const handleMouseMove = () => {
  showControls.value = true;
  clearTimeout(controlsTimer);
  controlsTimer = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false;
    }
  }, 3000);
};

// 监听视频源变化
watch(
  () => props.videoSrc,
  (newSrc) => {
    if (hls) {
      hls.destroy();
      hls = null;
    }
    if (newSrc && videoRef.value) {
      isLoading.value = true;
      if (newSrc.endsWith(".m3u8") && Hls.isSupported()) {
        hls = new Hls();
        hls.loadSource(newSrc);
        hls.attachMedia(videoRef.value);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          isLoading.value = false;
          if (props.autoplay) videoRef.value.play();
        });
        hls.on(Hls.Events.ERROR, () => {
          isLoading.value = false;
        });
      } else {
        videoRef.value.src = newSrc;
        videoRef.value.load();
        isLoading.value = false;
        if (props.autoplay) videoRef.value.play();
      }
    }
  }
);

onMounted(() => {
  document.addEventListener("keydown", handleKeydown);
  document.addEventListener("mousemove", handleMouseMove);
  if (props.videoSrc && videoRef.value) {
    if (props.videoSrc.endsWith(".m3u8") && Hls.isSupported()) {
      hls = new Hls();
      hls.loadSource(props.videoSrc);
      hls.attachMedia(videoRef.value);
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        isLoading.value = false;
        if (props.autoplay) videoRef.value.play();
      });
      hls.on(Hls.Events.ERROR, () => {
        isLoading.value = false;
      });
    } else {
      videoRef.value.src = props.videoSrc;
      if (props.autoplay) videoRef.value.play();
    }
  }
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeydown);
  document.removeEventListener("mousemove", handleMouseMove);
  clearTimeout(controlsTimer);
  clearTimeout(seekTimer);
  if (hls) {
    hls.destroy();
    hls = null;
  }
});

// 监听外部播放状态变化，同步本地状态
watch(() => props.isPlaying, (newVal) => {
  isPlaying.value = newVal;
});

// 暴露方法
defineExpose({
  play: () => videoRef.value?.play(),
  pause: () => videoRef.value?.pause(),
  seek,
  toggleFullscreen,
  setCurrentTime: (time) => {
    if (videoRef.value) videoRef.value.currentTime = time;
  },
  getCurrentTime: () => videoRef.value?.currentTime || 0,
  setPlaybackRate: (rate) => {
    if (videoRef.value) videoRef.value.playbackRate = rate;
  },
  getDuration: () => videoRef.value?.duration || 0,
});
</script>

<style scoped>
.video-player {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.2s ease;
}

.video-player:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.video-player.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  border-radius: 0;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.video-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-container.disable-click {
  cursor: not-allowed;
}

.play-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.play-button {
  width: 64px;
  height: 64px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
}

.play-button:hover {
  background: rgba(0, 0, 0, 0.8);
  transform: scale(1.1);
}

.loading-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: rgba(255, 255, 255, 0.9);
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 16px 12px 12px;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  backdrop-filter: blur(4px);
}

.video-controls.show {
  transform: translateY(0);
}

.controls-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.control-btn {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: white !important;
  width: 32px !important;
  height: 32px !important;
  min-height: 32px !important;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
}

.progress-container {
  flex: 1;
  margin: 0 8px;
}

.progress-slider {
  --el-slider-runway-bg-color: rgba(255, 255, 255, 0.3);
  --el-slider-main-bg-color: #409eff;
  --el-slider-button-size: 14px;
}

.time-display {
  color: white;
  font-size: 11px;
  font-family: "Courier New", monospace;
  white-space: nowrap;
  min-width: 70px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
  padding: 2px 6px;
  border-radius: 3px;
}

.volume-control {
  display: flex;
  align-items: center;
}

.seek-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 6px;
  pointer-events: none;
  font-size: 12px;
  backdrop-filter: blur(4px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .controls-row {
    gap: 8px;
  }

  .volume-control {
    display: none;
  }

  .time-display {
    font-size: 10px;
    min-width: 60px;
  }

  .control-btn {
    width: 28px !important;
    height: 28px !important;
    min-height: 28px !important;
  }
}
</style>
